﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Text;

namespace Dycox.Drawing
{
    public class PointFConverter : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            if (value is string)
            {
                float x, y;
                string text = (string)value;
                int p = text.IndexOf(',');

                if (p > 0 && p < text.Length - 1)
                {
                    if (float.TryParse(text.Substring(0, p), out x) &&
                        float.TryParse(text.Substring(p + 1), out y))
                        return new PointF(x, y);
                }

                throw new FormatException(text + " is not a valid PointF specification.");
            }

            return base.ConvertFrom(context, culture, value);
        }
    }
}
